import Footer from '@/components/Footer';
import { login } from '@/services/ant-design-pro/api';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import {
  AlipayCircleOutlined,
  DingtalkCircleFilled,
  LockOutlined,
  MobileOutlined,
  UserOutlined,
  WechatFilled,
} from '@ant-design/icons';
import type {
  ProFormInstance} from '@ant-design/pro-form';
import {
  LoginForm,
  ModalForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-form';
import {history } from 'umi';
import { Alert, message, Tabs } from 'antd';
import React, {useRef, useState} from 'react';
import {getVerityCode, recoverPassword} from "@/pages/User/Login/service";
import styles from './index.less';
import {Helmet} from "react-helmet";
import {useModel} from "@@/plugin-model/useModel";

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  /** 忘记密码窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  // ModalForm更新入口
  const formRef = useRef<ProFormInstance>();
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({
    access: "",
    currentAuthority: "",
    is_first_login: "",
    message: "",
    refresh: "",
    status: "",
    type: ""
  });
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');


  // 获取用户数据，菜单数据
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      const menus = await initialState?.fetchUserMenus?.();
      await setInitialState({
        ...initialState,
        currentUser: userInfo,
        menuData: menus,
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values, type});
      if (msg) {
        if (msg.access) {
          // 成功获取到token
          message.success('登录成功！');

          // 保存token
          localStorage.setItem('token', msg.access);
          localStorage.setItem('is_first_login', msg.is_first_login);

          // 保存refresh token
          localStorage.setItem('refresh', msg.refresh as string);
          await fetchUserInfo();

          // 跳转到登录前页面
          const historyPage = localStorage.getItem("loginRedirect")
          if (historyPage && historyPage.indexOf("login") === -1){
            history.push(historyPage)
            localStorage.removeItem("loginRedirect")
          }else{
            history.push('/');
          }
          return;
        } else {
          // 没有获取到token，用户名/密码错误
          message.error(msg.message);
        }
      }
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      console.log(error)
      message.error('登录失败，请重试！');
    }
  };
  const { status, type: loginType } = userLoginState;

  // 扫码登录方式
  function OauthLogin(t: string) {
    let info: string;
    if (t === 'Alipay') {

      info = '支付宝扫码登录未开放！'
    } else if (t === 'Wechat') {

      info = '微信扫码登录未开放！'
    } else {

      // 使用public下的dingtalk.html构造钉钉二维码扫码登录
      // window.location.href="/dingtalk.html"
      // return
      info = '钉钉扫码登录未开放！'
    }
    return message.error(info);
  }

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          登录页
        </title>
      </Helmet>
      <div className={styles.content}>
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="SG极简流水账"
          subTitle=" "
          initialValues={{
            autoLogin: true,
          }}
          actions={[
            "扫码登录",
            <AlipayCircleOutlined
              key="AlipayCircleOutlined"
              className={styles.icon}
              onClick={() => OauthLogin('Alipay')}
            />,
            <DingtalkCircleFilled
              key="DingTalkCircleOutlined"
              className={styles.icon}
              onClick={() => OauthLogin('DingTalk')}
            />,
            <WechatFilled
              key="WechatFilled"
              className={styles.icon}
              onClick={() => OauthLogin('Wechat')}
            />,
          ]}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
              {
                key: 'mobile',
                label: '手机号登录',
              },
            ]}
          />

          {status === 'error' && loginType === 'account' && (
            <LoginMessage
              content={"账户或密码错误！"}
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="account"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'用户名/手机号码/邮箱'}
                rules={[
                  {
                    required: true,
                    message: "请输入用户名!",
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！"
                  },
                ]}
              />
            </>
          )}

          {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="mobile"
                placeholder={'手机号'}
                rules={[
                  {
                    required: true,
                    message: "请输入手机号！"
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: "手机号格式错误！"
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} 获取验证码`;
                  }
                  return "获取验证码";
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: "请输入验证码！"
                  },
                ]}
                onGetCaptcha={async (phone) => {
                  const result = await getFakeCaptcha({
                    phone,
                  });
                  if (!result) {
                    return;
                  }
                  message.success('获取验证码成功！');
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
              onClick={() => {
                handleModalVisible(true);
              }}
            >忘记密码</a>
          </div>
        </LoginForm>
        <ModalForm
          title="找回密码"
          width="540px" // 注销可由其自动管理宽度
          visible={createModalVisible}
          formRef={formRef}
          onFinish={async (values) => {
            const res = await recoverPassword({ ...values });
            if (res) {
              if (res.status === 'done') {
                message.success(res.message);
                handleModalVisible(false);
                return true;
              } else {
                message.error(res.message);
                return false;
              }
            } else {
              message.error('恢复密码接口连接失败，请联系管理员！');
              return false;
            }
          }}
          onVisibleChange={handleModalVisible}
        >
          <ProFormText
            width="xl"
            fieldProps={{
              size: 'large'
            }}
            name="account"
            label="请输入您的账号/邮箱/手机号码"
            rules={[{ required: true, message: '账号/邮箱/手机号码不可为空！' }]}
          />
          <ProFormCaptcha
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={styles.icon} />,
            }}
            captchaProps={{
              size: 'large',
            }}
            placeholder= '请输入验证码'
            captchaTextRender={(timing, count) => {
              if (timing) {
                return `${count}获取验证码`
              }
              return '获取验证码'
            }}
            name="verityCode"
            rules={[
              {
                required: true,
                message: "请输入验证码！"
              },
            ]}
            onGetCaptcha={async () => {
              const account = formRef?.current?.getFieldValue('account');

              if (account) {
                const result = await getVerityCode({
                  account: account,
                });
                if (result) {
                  if (result.status === 'done') {
                    message.success('验证码获取成功，请登录您的邮箱查看！');
                  } else {
                    message.error(result.message);
                  }
                } else {
                  message.error('验证码接口访问失败，请联系管理员！');
                }
              } else {
                message.error('账号/邮箱/手机号码至少需要输入其中1个！');
              }
            }}
          />
          <ProFormText.Password
            width="xl"
            fieldProps={{
              size: 'large'
            }}
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '新密码不可为空！' },
              { min: 6, message: '密码至少需要6个字符！' },
            ]}
          />
        </ModalForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
